import 'package:chat_client/repositories/preferences_repository.dart';

/// 认证信息本地读写
class AuthRepository {
  // 私有构造函数，防止外部实例化
  AuthRepository._internal();

  // 静态变量，保存唯一实例
  static final AuthRepository _instance = AuthRepository._internal();

  // getter
  static AuthRepository get instance => _instance;

  // preference实例
  static final _prefs = Preferences.instance;

  // token
  static String? get token => _prefs.get<String>('token');

  // 储存认证信息
  Future<bool> setAuthInfo(
      {required String token,
      required String username,
      required String password}) async {
    // 使用 Preferences 存储认证信息
    await _prefs.set<String>('token', token);
    await _prefs.set<String>('username', username);
    await _prefs.set<String>('password', password);
    return false;
  }

  // 获取登录凭证
  Future<Map<dynamic, String?>> getLoginCertificate() async {
    final String? username = _prefs.get<String>('username');
    final String? password = _prefs.get<String>('password');

    return {'username': username, 'password': password};
  }

  // 清除认证信息
  Future<bool> clearAuthInfo() async {
    await _prefs.remove('token');
    await _prefs.remove('username');
    await _prefs.remove('password');
    return true;
  }

  // 是否已经本地储存
  Future<bool> isLocalStore(Future<void> Function() initAllInfo) async {
    final isLocalStore = _prefs.get<bool>('isLocalStore');
    if (isLocalStore == null || !isLocalStore) {
      // 执行本地初始化，拉取远程信息
      initAllInfo();
      // 标记为已初始化储存资料
      await _prefs.set<bool>('isLocalStore', true);
    }
    return true;
  }
}

// 用户个人信息本地存储
class UserRepository {
  // 单例
  UserRepository._internal();
  static final UserRepository _instance = UserRepository._internal();
  static UserRepository get instance => _instance;

  // preference实例
  static final _prefs = Preferences.instance;

  // 储存用户信息
  Future<bool> setUser(user) async {
    return await _prefs.setObject('user', user);
  }

  // 读取用户信息
  Future getUser() async {
    return _prefs.getObject('user');
  }

  // 修改部分用户信息
  Future<bool> updateUser(Map<String, dynamic> updatedFields) async {
    final user = await getUser();
    if (user == null) return false;

    updatedFields.forEach((key, value) {
      user[key] = value;
    });

    return await setUser(user);
  }
}
